<template>
  <div class="elx-imgbox page-picture-store">
    <div class="elx-imgbox-dialog">
      <div
        class="pick-block"
      >
        <div class="search-bar">
          <div class="input-row">
            <el-form
              :inline="true"
              :model="dataForm"
              @submit.prevent
            >
              <el-form-item>
                <el-input
                  v-model="fileName"
                  :placeholder="$t('pictureManager.picName')"
                  clearable
                  @keypress.enter="searchImg(true)"
                />
              </el-form-item>
              <el-form-item>
                <div
                  class="primary-btn default-btn"
                  @click="searchImg(true)"
                >
                  {{ $t("pictureManager.query") }}
                </div>
                <div
                  class="primary-btn default-btn"
                  :disabled="disabled"
                  @click="createGroup"
                >
                  {{ $t("resource.newGroup") }}
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="operation-bar">
          <div
            class="default-btn primary-btn"
            @click="uploadDialog"
          >
            {{ $t("pictureManager.uploadPic") }}
          </div>
        </div>
        <div class="box">
          <div class="group-box">
            <div class="group">
              <div class="group-item active-title">
                <span class="group-name">{{ $t("resource.groupName") }}</span>
                <span class="sidebar-operate">{{ $t("crud.menu") }}</span>
              </div>
              <div class="group-list">
                <div
                  :class="['group-item',groupId === 0 ?'active': '']"
                  @click="clickGroup(0)"
                >
                  <span class="group-name">{{ $t("pictureManager.allPictures") }}</span>
                </div>
                <div
                  v-for="(item) in groupList"
                  :key="item.attachFileGroupId"
                  :class="['group-item',groupId === item.attachFileGroupId ?'active': '']"
                >
                  <el-input
                    v-if="isUploadGroup && updateGroupId === item.attachFileGroupId"
                    ref="updateGroupNameRef"
                    v-model="createGroupName"
                    maxlength="6"
                    style="width: 210px"
                  >
                    <template #append>
                      <div @click="submitGroup">
                        <div style="width: 100%">
                          {{ $t('chat.confirm') }}
                        </div>
                      </div>
                    </template>
                  </el-input>
                  <span
                    v-else
                    class="group-name"
                    @click="clickGroup(item.attachFileGroupId)"
                  >
                    {{ item.name }}
                  </span>
                  <div class="sidebar-operate">
                    <div
                      class="default-btn text-btn"
                      @click="updateGroup(item.attachFileGroupId,item.name)"
                    >
                      {{ $t("resource.update") }}
                    </div>
                    <div
                      class="default-btn text-btn"
                      @click="deleteGroup(item.attachFileGroupId)"
                    >
                      {{ $t("resource.Delete") }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="isLoading"
            class="elx-img-list-loading"
          >
            <div class="el-icon-loading" />
          </div>
          <div
            v-else
            class="img-list"
          >
            <div class="elx-main elx-img-list">
              <div class="elx-head">
                <span class="text">
                  <el-checkbox
                    v-model="selectAll"
                    :indeterminate="isIndeterminate"
                    @change="selectAllEvent"
                  >
                    {{ $t("resource.selectAll") }}
                  </el-checkbox>
                </span>
                <span
                  class="text"
                  @click="delectImgs"
                >
                  {{ $t("resource.Delete") }}
                </span>
                <span
                  class="text"
                  @click="batchMove"
                >
                  {{ $t("resource.Move") }}
                </span>
              </div>
              <div class="img-item-con">
                <div
                  v-for="(img, itemIndex) in imgRes.records"
                  :key="itemIndex"
                  class="img-item"
                >
                  <div
                    class="thumb-wp"
                    @click="onClickListImage(img)"
                  >
                    <img-show :src="img.filePath" />
                  </div>
                  <input
                    v-if="isUpdateFileName && updateFileId === img.fileId"
                    ref="updateNameRef"
                    v-model="updateFileName"
                    type="text"
                    autofocus
                    maxlength="20"
                    style="width: 100px;outline: none;"
                    @blur="isUpdateFileName = false"
                    @keyup.enter="submitImgName"
                  >
                  <div
                    v-else
                    class="title"
                    @click="handleFileName(img)"
                  >
                    {{ img.fileName }}
                  </div>
                  <span
                    v-if="img.selected"
                    class="selected"
                    @click="onClickListImage(img)"
                  >
                    <el-icon
                      class="icon el-icon-check"
                    >
                      <Check />
                    </el-icon>
                  </span>
                </div>
              </div>
            </div>
            <div
              v-if="!imgRes.records.length"
              class="data-tips"
            >
              {{ $t("order.noData") }}
            </div>
            <el-pagination
              layout="total, prev, pager, next, jumper"
              :current-page="imgRes.current"
              :page-size="imgRes.size"
              :total="imgRes.total"
              class="pagination"
              @current-change="onPageNumChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 批量移动分组 -->
    <el-dialog
      v-model="showBatchMove"
      :title="$t('resource.mobileGroup')"
      :close-on-click-modal="false"
      top="200px"
      :append-to-body="showBatchMove"
      width="500px"
    >
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="groupFormRef"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item :label="$t('resource.group')">
          <el-select
            v-model="selectGroup"

            :placeholder="$t('resource.selectGroup')"
          >
            <el-option
              v-for="item in groupList"
              :key="item.attachFileGroupId"
              :label="item.name"
              :value="item.attachFileGroupId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="showBatchMove = false"
          >
            {{ $t("resource.cancel") }}
          </div>
          <div
            class="primary-btn default-btn"
            @click="submitBatchMove()"
          >
            {{ $t("resource.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- /批量移动分组 -->
    <upload-pic
      v-if="uploadDialogVisible"
      ref="uploadPicRef"
      @get-img-list-data="loadListImage(1)"
      @handle-dialog-close="handleDialogClose"
      @get-group-data="getGroupList"
    />
    <group-add-or-update
      v-if="groupVisible"
      ref="groupAddOrUpdateRef"
      @get-group-data="getGroupList"
    />
  </div>
</template>

<script setup>
import uploadPic from './upload-pic.vue'
import { Debounce } from '@/utils/debounce'
import { ElMessage, ElMessageBox } from 'element-plus'

const dataForm = reactive({})
const disabled = ref(false)

const selectGroup = ref('')
const updateFileId = ref('')
const updateFileName = ref('')
const isUpdateFileName = ref(false)
const updateNameRef = ref(null)
const handleFileName = (img) => {
  selectGroup.value = img.attachFileGroupId
  updateFileId.value = img.fileId
  updateFileName.value = img.fileName
  isUpdateFileName.value = true
  nextTick(() => { // 2. 弹框显示DOM更新完成后 获取refs.ref1 设置焦点
    updateNameRef.value[0]?.focus() // 设置焦点
  })
}

const uploadDialogVisible = ref(false)
const uploadPicRef = ref(null)
const uploadDialog = () => {
  uploadDialogVisible.value = true
  nextTick(() => {
    uploadPicRef.value?.show()
  })
}

let images = [] // 已选图片

const imgRes = ref({
  records: [],
  current: 1
})
/**
 * 提交修改后的图片名称
 */
const submitImgName = () => {
  http({
    url: http.adornUrl('/admin/file/updateFile'),
    method: 'put',
    data: http.adornData({
      fileId: updateFileId.value,
      fileName: updateFileName.value,
      attachFileGroupId: selectGroup.value,
      type: 1
    })
  }).then(() => {
    ElMessage({
      type: 'success',
      message: $t('resource.updateSuccess')
    })
    updateFileName.value = ''
    selectGroup.value = ''
    isUpdateFileName.value = false
    loadListImage(imgRes.value.current)
  }).catch(() => {
  })
}

let fileIds = [] // 已选图片的fileId
const selectAll = ref(false)
/**
 * 批量删除图片
 */
const delectImgs = () => {
  if (!fileIds.length) {
    ElMessage({
      message: $t('pictureManager.tips1'),
      type: 'error',
      duration: 1000
    })
    return
  }
  ElMessageBox.confirm($t('pictureManager.tips3'), $t('resource.tips'), {
    confirmButtonText: $t('resource.confirm'),
    cancelButtonText: $t('resource.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/admin/file/deleteByIds'),
      method: 'delete',
      data: fileIds
    }).then(() => {
      images = []
      fileIds = []
      selectAll.value = false
      selectAllEvent()
      loadListImage()
    })
  })
}

const showBatchMove = ref(false)
/**
 * 批量移动分组
 */
const batchMove = () => {
  if (!fileIds.length) {
    ElMessage({
      message: $t('pictureManager.tips1'),
      type: 'error',
      duration: 1000
    })
    return
  }
  showBatchMove.value = true
}

const isIndeterminate = ref(false)
const submitBatchMove = () => {
  http({
    url: http.adornUrl('/admin/file/batchMove'),
    method: 'put',
    data: {
      fileIds,
      attachFileGroupId: selectGroup.value
    }
  }).then(() => {
    images = []
    fileIds = []
    showBatchMove.value = false
    selectAll.value = false
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1000,
      onClose: () => {
        loadListImage()
        isIndeterminate.value = false
      }
    })
  })
}
/**
 * 点击图片时选中或取消选中图片
 * @param img object
 */
const onClickListImage = (img) => {
  // 多选图片-如果已选中则取消选中
  const imgIndex = selectedImageIndex(img)
  if (img.selected) {
    // 取消图片已选状态
    img.selected = false
    images.splice(imgIndex, 1)
    fileIds.splice(imgIndex, 1)
  } else {
    img.selected = true
    images.push(JSON.parse(JSON.stringify(img)))
    fileIds.push(img.fileId)
  }

  // 全选按钮状态
  const everyRes = imgRes.value.records.every(imgItem => imgItem.selected)
  selectAll.value = everyRes // 当前页面的图片是否全选
  isIndeterminate.value = !everyRes
}

/**
 * 按图片名称搜索图片
 */
const searchImg = (newData = false) => {
  loadListImage(1, newData)
}

const isLoading = ref(true)
let tempSearchForm = null // 保存上次点击查询的请求条件
const groupId = ref(0) // 点击分组
const fileName = ref('')
const isUploadGroup = ref(false)
/**
 * 加载图片列表数据
 * @param current
 * @param newData
 */
const loadListImage = (current, newData = false) => {
  isLoading.value = true
  if (newData || !tempSearchForm) {
    tempSearchForm = {
      current,
      size: 30,
      fileName: fileName.value ? fileName.value : null,
      attachFileGroupId: groupId.value,
      type: 1
    }
  } else {
    tempSearchForm = {
      fileName: tempSearchForm.fileName,
      ...{
        current,
        size: 30,
        attachFileGroupId: groupId.value,
        type: 1
      }
    }
  }
  http({
    url: http.adornUrl('/admin/file/attachFilePage'),
    method: 'get',
    params: http.adornParams(tempSearchForm)
  }).then(({ data }) => {
    imgRes.value = data
    let existCount = 0
    imgRes.value.records.forEach(img => {
      if (isExist(img)) {
        existCount++
        img.selected = true
      } else {
        img.selected = false
      }
    })
    isLoading.value = false
    selectAll.value = imgRes.value.records.length !== 0 && imgRes.value.records.length === existCount
    isIndeterminate.value = !!(existCount && imgRes.value.records.length !== existCount)
    isUploadGroup.value = false
  })
}

const isExist = (img) => {
  for (let i = 0; i < images.length; i++) {
    if (img.fileId === images[i].fileId) {
      return true
    }
  }
  return false
}

/**
 * 图片已选则返回下标，未选则返回-1
 */
const selectedImageIndex = (img) => {
  for (let i = 0; i < images.length; i++) {
    const selectedImg = images[i]
    if (selectedImg.fileId === img.fileId) {
      return i
    }
  }
  return -1
}

/**
 * 分页页面变化时刷新数据
 * @param page
 */
const onPageNumChange = (page) => {
  loadListImage(page)
}

const groupList = ref([]) // 分组列表
/**
 * 获取分组列表
 */
const getGroupList = () => {
  http({
    url: http.adornUrl('/admin/fileGroup/list'),
    method: 'get',
    params: {
      type: 1 // 1、图片 2、视频 3、文件
    }
  }).then(res => {
    groupList.value = res.data
  })
}
/**
 * 点击分组
 */
const clickGroup = (id) => {
  groupId.value = id
  loadListImage()
}

const updateGroupId = ref(0) // 修改分组的id
const createGroupName = ref('') // 新建分组名
const updateGroupNameRef = ref(null)
const updateGroup = (id, name) => {
  updateGroupId.value = id
  createGroupName.value = name
  isUploadGroup.value = true
  nextTick(() => {
    // 2. 弹框显示DOM更新完成后 获取refs.ref1 设置焦点
    // 设置焦点
    updateGroupNameRef.value[0].focus()
  })
}

const groupVisible = ref(false)
const groupAddOrUpdateRef = ref(null)
const createGroup = () => {
  groupVisible.value = true
  nextTick(() => {
    groupAddOrUpdateRef.value?.show(1)
  })
}

/**
 * 新建分组
 */
const submitGroup = Debounce(() => {
  if (!createGroupName.value.trim()) {
    return ElMessage.error($t('resource.CannotBeEmpty'))
  }
  const method = 'put'
  const param = {
    name: createGroupName.value,
    type: 1 // 1、图片 2、视频 3、文件
  }
  param.attachFileGroupId = updateGroupId.value
  http({
    url: http.adornUrl('/admin/fileGroup'),
    method,
    data: param
  }).then(() => {
    ElMessage({
      message: $t('resource.successTips1'),
      type: 'success',
      duration: 1000,
      onClose: () => {
        isUploadGroup.value = false
        getGroupList()
      }
    })
  })
})

const deleteGroup = (id) => {
  ElMessageBox.confirm($t('pictureManager.tips2'), $t('resource.tips'), {
    confirmButtonText: $t('resource.confirm'),
    cancelButtonText: $t('resource.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/admin/fileGroup'),
      method: 'delete',
      params: {
        attachFileGroupId: id
      }
    }).then(() => {
      getGroupList()
    })
  })
}

/**
 * 全选图片事件
 */
const selectAllEvent = () => {
  if (selectAll.value) {
    imgRes.value.records.forEach(img => {
      // 当其为未选中状态时才push，防止重复添加数据
      if (!img.selected) {
        images.push(JSON.parse(JSON.stringify(img)))
        fileIds.push(img.fileId)
        img.selected = true
      }
    })
  } else {
    imgRes.value.records.forEach(img => {
      img.selected = false
    })
    fileIds = []
    images = []
  }
  isIndeterminate.value = false
}

/**
 * 关闭回调
 */
const handleDialogClose = () => {
  fileName.value = ''
  uploadDialogVisible.value = false
}

onMounted(() => {
  getGroupList()
  loadListImage()
})

</script>

<style lang="scss" scoped>
@use "index";
</style>
